using System;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace sstchur.web.SmartNav
{
	/// <summary>
	/// Summary description for SmartScroller.
	/// </summary>
	public class SmartScroller : System.Web.UI.Control
	{
		private HtmlForm m_theForm = null;
		
		public SmartScroller()
		{
		}
		
		private void GetServerForm(Control parent, ref HtmlForm form)
		{
			if (parent is HtmlForm)			
				form = (HtmlForm)parent;			
			else			
				if (parent.HasControls())
				foreach (Control child in parent.Controls)
					GetServerForm(child, ref form);
		}

		protected override void OnInit(EventArgs e)
		{
			GetServerForm(Page, ref m_theForm);
			if (m_theForm == null)
				return;			
										
			HtmlInputHidden hidScrollLeft = new HtmlInputHidden();
			hidScrollLeft.ID = "scrollLeft";
	
			HtmlInputHidden hidScrollTop = new HtmlInputHidden();
			hidScrollTop.ID = "scrollTop";
	
			this.Controls.Add(hidScrollLeft);
			this.Controls.Add(hidScrollTop);						
	
			string scriptString = @"
<!-- sstchur.web.SmartNav.SmartScroller ASP.NET Generated Code -->
<script language = ""javascript"">
<!--
  function sstchur_SmartScroller_GetCoords()
  {
    var scrollX, scrollY;
    if (document.all)
    {
      if (!document.documentElement.scrollLeft)
        scrollX = document.body.scrollLeft;
      else
        scrollX = document.documentElement.scrollLeft;

      if (!document.documentElement.scrollTop)
        scrollY = document.body.scrollTop;
      else
        scrollY = document.documentElement.scrollTop;
    }
    else
    {
      scrollX = window.pageXOffset;
      scrollY = window.pageYOffset;
    }
    document.forms[""" + m_theForm.ClientID + @"""]." + hidScrollLeft.ClientID + @".value = scrollX;
    document.forms[""" + m_theForm.ClientID + @"""]." + hidScrollTop.ClientID + @".value = scrollY;
  }


  function sstchur_SmartScroller_Scroll()
  {
    var x = document.forms[""" + m_theForm.ClientID + @"""]." + hidScrollLeft.ClientID + @".value;
    var y = document.forms[""" + m_theForm.ClientID + @"""]." + hidScrollTop.ClientID + @".value;
    window.scrollTo(x, y);
  }

  
  window.onload = sstchur_SmartScroller_Scroll;
  window.onscroll = sstchur_SmartScroller_GetCoords;
  window.onclick = sstchur_SmartScroller_GetCoords;
  window.onkeypress = sstchur_SmartScroller_GetCoords;
// -->
</script>
<!-- End sstchur.web.SmartNav.SmartScroller ASP.NET Generated Code -->";

			Page.RegisterStartupScript("SmartScroller", scriptString);
		}

		protected override void Render(HtmlTextWriter writer)
		{
			Page.VerifyRenderingInServerForm(this);
			base.Render(writer);
		}
	}
}
